

import glUtils from "../utils/glUtils";

/**
 * desc:
 *  实例绘制
 */

const vs = `#version 300 es

layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec4 vColor;

layout(location = 2) in vec4 posOffset; // 每个实例更新一次

out vec4 color;
void main() {
    // 注意 w 会变成2   然后归一化的时候 会缩放. 所以需要手动设置 w 为 1.0
    vec4 pos = vPosition + posOffset;
    pos.w = 1.0;
    gl_Position = pos;
    color = vColor;
}
`;

const fs = `#version 300 es
precision mediump float;

in vec4 color;
out vec4 fColor;

void main() {
    fColor = color;
}
`;

export default  {

    gl:null,
    bInited:false,

    // handle
    vPosition:0,
    vColor:1,
    posOffset:2,

    init(gl){
        this.gl = gl;

        this.program = glUtils.createProgram(gl,vs,fs);


        let vertices = [
            0,0.5,
            -0.5,-0.5,
            0.5,-0.5
        ].map((num,idx)=>{
            let even = idx % 2 === 0;
            if(even){
                return num * 0.25 - 1;
            }else{
                return  num * 0.25;
            }
        });

        console.log('vertices:',vertices);

        let colors = [
            1,0,0,1,
            0,1,0,1,
            0,0,1,1
        ];

        // 绘制4个
        let lstPosOffset = [
            0.25,0,
            0.25,0,
            0.25,0,
            0.25,0,
        ].map((num,idx)=>{
            return num * idx;
        });
        console.log('lstPosOffset:',lstPosOffset);

        this.vao = gl.createVertexArray();
        gl.bindVertexArray(this.vao);

        const ItemSize = Float32Array.BYTES_PER_ELEMENT;
        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER,ItemSize * (vertices.length + colors.length + lstPosOffset.length),gl.STATIC_DRAW);

        gl.bufferSubData(gl.ARRAY_BUFFER,0,new Float32Array(vertices));
        gl.bufferSubData(gl.ARRAY_BUFFER,ItemSize * vertices.length,new Float32Array(colors));
        gl.bufferSubData(gl.ARRAY_BUFFER,ItemSize * (vertices.length + colors.length), new Float32Array(lstPosOffset));

        gl.enableVertexAttribArray(this.vPosition);
        gl.vertexAttribPointer(this.vPosition,2,gl.FLOAT,false,0,0);

        gl.enableVertexAttribArray(this.vColor);
        gl.vertexAttribPointer(this.vColor,4,gl.FLOAT,false,0,ItemSize * vertices.length);

        gl.enableVertexAttribArray(this.posOffset);
        gl.vertexAttribPointer(this.posOffset,2,gl.FLOAT,false,0,ItemSize * (vertices.length + colors.length));
        gl.vertexAttribDivisor(this.posOffset,1);

        gl.bindVertexArray(null);
        this.bInited = true;
    },

    render(){
        if(!this.bInited){
            return;
        }

        let gl = this.gl;

        gl.useProgram(this.program);
        gl.bindVertexArray(this.vao);
        gl.drawArraysInstanced(gl.TRIANGLES,0,3,4);
        gl.bindVertexArray(null);
    },
}